package com.kfm.hotel.controller;

import com.anji.captcha.util.AESUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kfm.hotel.domain.SysUser;
import com.kfm.hotel.service.MailService;
import com.kfm.hotel.service.SysUserService;
import com.kfm.hotel.util.Constant;
import com.kfm.hotel.util.MD5Util;
import com.kfm.hotel.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.mail.MessagingException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
@Slf4j
public class LoginController {


    @Autowired
    private SysUserService service;

    @Autowired
    private MailService mailService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @GetMapping({"/", "/login"})
    public ModelAndView login(){
        ModelAndView mv = new ModelAndView("login");
        return mv;
    }

    @GetMapping({"/email"})
    public ModelAndView email(){
        ModelAndView mv = new ModelAndView("email");
        return mv;
    }

    @PostMapping({"/email"})
    public R sendEmail(String email, HttpSession session) throws MessagingException {
        // TODO 根据邮箱查询用户, 如果用户存在，发送邮件
        int code = mailService.sendLoginCodeEmail(email);
        // 保存验证码到 session
        session.setAttribute(Constant.LOGIN_CODE, code);
        return R.ok(email);
    }



//    @PostMapping("/login")
//    public R login(@RequestBody SysUser user, HttpServletResponse response, HttpSession session) throws Exception {
//        // 密码 AES 解密
//        String pass = AESUtil.aesDecrypt(user.getPassword(), user.getKey());
//        user.setPassword(MD5Util.MD5(pass, user.getUsername()));
//
//        try{
//            // security 登录
//            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
//            // 会调用 UserDetailsService.loadUserByUsername
//            Authentication authentication = authenticationManager.authenticate(token);
//            // 没有异常，登录成功
//            // 获取用户信息
//            SecurityContextHolder.getContext().setAuthentication(authentication);
//            log.info(authentication.getPrincipal().toString());
//            // TODO(使用 security 实现记住我功能)
//            if (user.getRememberMe() != null && user.getRememberMe()){
//                // 记住我功能
//                extracted(user, response, pass);
//            }
//            // 登录成功，将用户信息存入 session
//            session.setAttribute(Constant.LOGIN_USER, authentication.getPrincipal());
//            // 登录成功，重定向到首页
//            return R.ok("登录成功", "/index");
//
//        } catch (Exception e){
//            return R.fail("用户名或密码错误");
//        }
//    }

    @GetMapping("/index")
    public ModelAndView index(@SessionAttribute(value = Constant.LOGIN_USER) SysUser user){
        ModelAndView modelAndView = new ModelAndView("index");
        modelAndView.addObject("name", user.getName());
        return modelAndView;
    }

    @GetMapping("/welcome")
    public ModelAndView welcome(){
        ModelAndView modelAndView = new ModelAndView("welcome");
        return modelAndView;
    }

    @GetMapping("/logout")
    public ModelAndView logout(HttpSession session, HttpServletResponse response){
        // 退出登录，删除session中的用户信息
        session.removeAttribute(Constant.LOGIN_USER);
        // 退出登录，删除cookie
        Cookie cookie = new Cookie(Constant.REMEMBER_ME_COOKIE_NAME, "");
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
        return new ModelAndView("redirect:/login");
    }

    private static void extracted(SysUser user, HttpServletResponse response, String pass) throws Exception {
        /*
         记住我功能7天免登录如何实现？
            1. 生成一个cookie，存储用户名，密码。用 AES加密，然后使用 -- 分隔
            2. 设置cookie的有效期为7天
            3. 设置cookie的作用域为根目录
            4. 将cookie添加到响应头中
         */
        String enUsername = AESUtil.aesEncrypt(user.getUsername(), Constant.REMEMBER_ME_AES_KEY);
        String enPass = AESUtil.aesEncrypt(pass, Constant.REMEMBER_ME_AES_KEY);
        String value = enUsername + Constant.REMEMBER_ME_COOKIE_SPLIT_CHAR + enPass;
        Cookie cookie = new Cookie(Constant.REMEMBER_ME_COOKIE_NAME, value);
        cookie.setMaxAge(60 * 60 * 24 * 7);
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}
